package org.example.socket.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioTcpServer {

    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws IOException {

        try (ServerSocket serverSocket = new ServerSocket(8888)) {

            if (args.length > 0) {
                while (true) {
                    Socket acceptSocket = serverSocket.accept();
                    executor.submit(() -> process(acceptSocket));
                }
            } else {
                while (true) {
                    Socket acceptSocket = serverSocket.accept();
                    new Thread(() -> process(acceptSocket)).start();
                }
            }
        }
    }

    private static void process(Socket acceptSocket) {

        try (InputStream is = acceptSocket.getInputStream();
             OutputStream os = acceptSocket.getOutputStream()) {
            long startT = System.currentTimeMillis();
            byte[] b = new byte[512];
            if (-1 != is.read(b)) {
                System.out.print("recv client msg:" + new String(b));
            }
            os.write("I am server".getBytes(StandardCharsets.UTF_8));
            os.flush();
            System.out.println("/ acc:" + (System.currentTimeMillis() - startT));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
